<template>
	<div>
		<el-card shadow="hover">
			<div class=" mb15">
				<el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="100px">
					<el-row>
						<el-col :span="8" >
							<el-form-item label="日期">
								<el-date-picker v-model="tableData.dateRange" type="datetimerange" size="default"
									style="width: 300px" range-separator="-" start-placeholder="开始日期"
									end-placeholder="结束日期"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8" >
							<el-form-item label="企业名称" prop="companyName">
								<el-input v-model="tableData.param.companyName" placeholder="请输入企业名称" clearable
									@keyup.enter.native="getList" />
							</el-form-item>
						</el-col>
						<el-col :span="8" >
							<el-form-item>
								<el-button type="primary" @click="getList"><el-icon>
										<Search />
									</el-icon>搜索</el-button>
								<el-button @click="resetQuery(queryRef)"><el-icon>
										<Refresh />
									</el-icon>重置</el-button>
                                <el-button type="primary" v-if="permissionStore.isPermissionsBtn('009005001')" @click="exportFile"><el-icon><Download /></el-icon> 导出</el-button>
							</el-form-item>
						</el-col>
						
					</el-row>
				</el-form>
			</div>
			<el-table v-loading="loading" :data="tableData.data">
				<el-table-column label="日期" align="center" prop="time" min-width="100px" />
				<el-table-column label="企业" align="center" prop="companyName" min-width="100px" />
				<el-table-column label="卡号" align="center" prop="phone" min-width="100px" />
				<el-table-column label="话费" align="center" prop="amount" min-width="100px" />
			</el-table>
			<pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNumber"
				v-model:limit="tableData.param.pageLength" @pagination="getList" />
		</el-card>
	</div>
</template>
<script lang="ts">
import { companyConsumptionApi } from '@/api/financeCenter/dailyExpenditure';
import { toRefs, reactive, onMounted, ref, defineComponent, computed, getCurrentInstance, toRaw } from 'vue';
import { FormInstance } from 'element-plus';
import { usePermissionStore } from "@/store/modules/permission"
import {getFile} from '@/utils/excel/excelUtil'
export default defineComponent({
	name: 'dailyExpenditureList',   //企业每日花费
	setup() {
		const { proxy } = <any>getCurrentInstance();
		const loading = ref(false);
		const queryRef = ref();
		const permissionStore = usePermissionStore()
		const state = reactive({
			ids: [],
			tableData: {
				data: [],
				total: 0,
				loading: false,
				dateRange: [],
				param: {
					pageNumber: 1,
					pageLength: 10,
					beginTime: null,
					endTime: null,
					companyName:undefined,
				},
			},
		});
		// 页面加载时
		onMounted(() => {
			initTableData();
		});
		// 初始化表格数据
		const initTableData = () => {
			getList();
		};
		/** 重置按钮登录 */
		const resetQuery = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			formEl.resetFields();
			state.tableData.dateRange = []
			getList();
		};
		// 获取列表数据
		const getList = () => {
			loading.value = true;
			const obj = getBeginEndTime(state.tableData.dateRange)
			Object.assign(state.tableData.param, obj);
			companyConsumptionApi(state.tableData.param).then((res: any) => {
				let list = res.data.list ?? [];
				state.tableData.data = list.map(item => {
                    item.time = formatYearMonth(item.date)
                    console.log(item.time);

                    return item
                })
				console.log(state.tableData.data);
				state.tableData.total = res.data.total;
				loading.value = false;
			});
		};

		function getBeginEndTime(arr) {
            // 如果数组为空，返回 beginTime 和 endTime 都为 null 的对象
            if (arr.length === 0) {
                return {
                    beginTime: null,
                    endTime: null
                };
            }

            // 定义一个函数，用于将日期字符串格式化为年月日
            function formatDate(dateStr) {
                let date = new Date(dateStr);
                let year = date.getFullYear();
                let month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
                let day = String(date.getDate()).padStart(2, "0");
                return `${year}${month}${day}`;
            }

            // 格式化数组中的第一个日期为 beginTime
            let beginTime = formatDate(arr[0]);
            // 格式化数组中的最后一个日期为 endTime
            let endTime = formatDate(arr[arr.length - 1]);

            // 返回包含 beginTime 和 endTime 的对象
            return {
                beginTime: beginTime,
                endTime: endTime
            };
        }

        function formatYearMonth(dateStr) {
            dateStr+=''
            // 检查输入字符串是否符合预期格式（8位数字，如202507）
            if (dateStr.length !== 8) {
                return ''
            }

            // 截取年份和月份
            let year = dateStr.substring(0, 4);
            let month = dateStr.substring(4, 6);
            let day = dateStr.substring(6, 8);

            // 返回格式化后的字符串
            return `${year}-${month}-${day}`;
        }

		
		
		// 导出文件
		const exportFile = async () => {
			getFile('/system/company/consumption/day/export','企业每日花费数据')
		}
		return {
			proxy,
			loading,
			queryRef,
			permissionStore,
			resetQuery,
			exportFile,
			getList,
			...toRefs(state),
		};
	},
});
</script>
